package com.xoa.service.inv.impl;

import com.xoa.dao.crm.CustomerMapper;
import com.xoa.dao.inv.InvWarehouseMapper;
import com.xoa.dao.inv.OmReturnMapper;
import com.xoa.dao.inv.PoCommodityEnterMapper;
import com.xoa.dao.inv.ProductTypeMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.inv.OmReturn;
import com.xoa.model.inv.PoCommodityEnter;
import com.xoa.model.inv.ProductType;
import com.xoa.model.users.Users;
import com.xoa.service.inv.OmReturnService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class SalesReturnServiceImpl implements OmReturnService {
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private PoCommodityEnterMapper poCommodityEnterMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private InvWarehouseMapper invWarehouseMapper;
    @Autowired
    private OmReturnMapper omReturnMapper;
    @Resource
    private ProductTypeMapper productTypeMapper;
    /**
     * 查询所有
     */
    @Override
    public List<OmReturn> selectAll(Map<String, Object> map) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<OmReturn> omReturns = omReturnMapper.selectAll(map);
        List<OmReturn> news = new ArrayList<>();
        for (OmReturn omReturn : omReturns
        ) {
            omReturn.setReturnDateStr(format.format(omReturn.getReturnDate()));
            omReturn.setShipper(usersMapper.findUserByuid(omReturn.getUserId()).getUserName());
            omReturn.setCustomerName(customerMapper.selectByPrimaryKey(omReturn.getCustomerId()).getCustomerName());
            omReturn.setWarehouseName(invWarehouseMapper.selectByPrimaryKey(omReturn.getWarehouseId()).getWarehouseName());
            //商品大类名称
            if (omReturn.getEnterId()!=null) {
                PoCommodityEnter poCommodityEnter = poCommodityEnterMapper.selectByPrimaryKey(omReturn.getEnterId());
              if(poCommodityEnter!=null){
                ProductType productType = productTypeMapper.selectByPrimaryKey(Integer.valueOf(poCommodityEnter.getProductType()));
                if (productType != null) {
                    omReturn.setProductType(productType.getProductTypeName());
                }
              }
            }
            news.add(omReturn);
        }
        return news;
    }

    /**
     * 数据回显接口
     */
    @Override
    public OmReturn selectByPrimaryKey(Integer returnId) {
        OmReturn omReturn = omReturnMapper.selectByPrimaryKey(returnId);
        omReturn.setReturnDateStr(DateFormat.getStrDate(omReturn.getReturnDate()));
        omReturn.setShipper(usersMapper.findUserByuid(omReturn.getUserId()).getUserName());
        omReturn.setCustomerName(customerMapper.selectByPrimaryKey(omReturn.getCustomerId()).getCustomerName());
        omReturn.setWarehouseName(invWarehouseMapper.selectByPrimaryKey(omReturn.getWarehouseId()).getWarehouseName());
        return omReturn;
    }

    /**
     * 根据主键id进行删除(逻辑删除)
     */
    @Override
    public int deleteByPrimaryKey(Integer returnId) {
        return omReturnMapper.deleteByPrimaryKey(returnId);
    }

    /**
     * 添加出货数据
     */
    @Override
    public int insertSales(OmReturn omReturn, Map<String, Object> maps) {
        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        Map<String, Object> map =new HashMap<>();
        map.put("enterId",omReturn.getEnterId());
        map.put("num",omReturn.getReturnNum());
        map.put("way",1);
        poCommodityEnterMapper.updateByEnterId(map);
        omReturn.setUserId(users.getUid());
        Date date = new Date();//当前日期---生成单据号的主要因素
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String timeStr = format.format(date);
        String stt = "NO";//固定前缀
        int newNumber = 00001;//自增编号
        String documentNo = "";
        if (omReturn != null) {
            Map<String, Object> mapa = new HashMap<>();
            mapa.put("obj", new OmReturn());
            List<OmReturn> list = omReturnMapper.selectAll(mapa);
            if (list.size() > 0 && list != null) {
                if (list.get(0).getDocumentNo() != null && !list.get(0).getDocumentNo().isEmpty()) {
                    String str = list.get(0).getDocumentNo().substring(10);
                    int newNo = Integer.parseInt(str) + 1;
                    String dtr = String.format("%05d", newNo);
                    documentNo = stt + timeStr + dtr;
                }
                omReturn.setDocumentNo(documentNo);
            } else {
                String dtr = String.format("%05d", newNumber);
                documentNo = stt + timeStr + dtr;
                omReturn.setDocumentNo(documentNo);
            }

        }
        return omReturnMapper.insert(omReturn);
    }

    /**
     * 更新数据(根据产品id)
     */
    @Override
    public int updateByPrimaryKeySelective(OmReturn omReturn, String productType, String enterName, String enterSpecs, String enterCode) {
        ProductType type = productTypeMapper.selectProductTypeByName(productType);
       /* if (type.getProductTypeId() != 0) {
            omReturn.setEnterId(type.getProductTypeId());
        }*/
        return omReturnMapper.updateByPrimaryKeySelective(omReturn);
    }

    /**
     * 出货信息表导出功能
     */
    @Override
    public ToJson<OmReturn> ExportOmReturn(HttpServletRequest request, HttpServletResponse response, OmReturn omReturn, String beginDate, String isExport) {
        ToJson<OmReturn> json = new ToJson<OmReturn>();
        try {
            Map<String, Object> maps =new HashMap<>();
            maps.put("obj", new OmReturn());
            List<OmReturn> omReturnList = omReturnMapper.selectAll(maps);
            List<OmReturn> omReturns = new ArrayList<>();
            for (OmReturn omReturn1 : omReturnList) {
                if (omReturn1.getReturnDate() != null) {
                    omReturn1.setReturnDateStr(DateFormat.getStrDate(omReturn1.getReturnDate()));
                    omReturn1.setShipper(usersMapper.findUserByuid(omReturn1.getUserId()).getUserName());
                    omReturn1.setCustomerName(customerMapper.selectByPrimaryKey(omReturn1.getCustomerId()).getCustomerName());
                    omReturn1.setWarehouseName(invWarehouseMapper.selectByPrimaryKey(omReturn1.getWarehouseId()).getWarehouseName());
                    omReturn1.setOutNum(-omReturn1.getReturnNum());
                    omReturn1.setOutNumTotal(-omReturn1.getReturnTotal());
                }
                omReturns.add(omReturn1);
            }
            //条件判断[后端拼接条件进行判断]
            if ("yes".equals(isExport)) {
                // 设置Excel表头标题
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("销售退货表", 13);
                // 设置Excel表的字段名
                String[] secondTitles = {"商品大类", "商品名称", "商品规格", "商品编码", "退货日期", "退货数量", "退货单价", "退货合计", "客户", "退货人", "出库数量", "合计", "仓库", "备注"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                // 字段名对应的实体类属性名称
                String[] beanProperty = {"productType", "enterName", "enterSpecs", "enterCode", "returnDateStr", "returnNum", "returnPrice", "returnTotal", "customerName", "shipper", "outNum", "outNumTotal", "warehouseName", "returnRemark"};
                HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, omReturns, beanProperty);
                ServletOutputStream out = response.getOutputStream();
                // 设置Excel表的导出名称
                String filename = "销售退货表.xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
                json.setFlag(0);
                json.setMsg("true");
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }
    //查询所有出货人
    @Override
    public ToJson<OmReturn> selectUsers() {
        ToJson<OmReturn> json = new ToJson<OmReturn>();
        List<OmReturn> omReturns = omReturnMapper.selectUsers();
        for (OmReturn omReturn : omReturns) {
            omReturn.setShipper(usersMapper.findUserByuid(omReturn.getUserId()).getUserName());
        }
        json.setMsg("ok");
        json.setFlag(0);
        json.setObj(omReturns);
        return json;
    }
}
